/*  * Author: 凌逆战 | Never
 * * Data: 2023/7/5
 * * Description:
 */
#include <stdio.h>
#include "resampler.h"
#include "common.h"
#include "data_utils.h"


int main(int argc, char const* argv[]) {
    FILE* fp_in = fopen("../file/96k-white.pcm", "rb");
    FILE* fp_16kHz = fopen("../file/16kHz_white.pcm", "wb");
    FILE* fp_96kHz = fopen("../file/96kHz_white.pcm", "wb");

    int i, r;
    unsigned long read_samples;
    short in_buf_96k_i16[FRAME_LEN_96K] = {0};
    short out_buf_96k_i16[FRAME_LEN_96K] = {0};
    float in_buf_96k_f32[FRAME_LEN_96K] = {0.0f};
    float out_buf_96k_f32[FRAME_LEN_96K] = {0.0f};

    short in_buf_16k_i16[FRAME_LEN_16K] = {0};
    short out_buf_16k_i16[FRAME_LEN_16K] = {0};
    float in_buf_16k_f32[FRAME_LEN_16K] = {0};
    float out_buf_16k_f32[FRAME_LEN_16K] = {0};

    float mem_downsampling[4 * PSAP_BIQUAD_ORDER] = {0.0f};  // 用于下采样低通滤波器
    float mem_upsampling[4 * PSAP_BIQUAD_ORDER] = {0.0f};    // 用于上采样低通滤波器

    static float old_bufR_end = 0.0f;

    while ((read_samples = fread(in_buf_96k_i16, sizeof(short), FRAME_LEN_96K, fp_in)) != 0) {
        if (read_samples != FRAME_LEN_96K) {
            printf("read_samples: %ld\n", read_samples);
            break;
        }

        convert_i16_to_f32(in_buf_96k_i16, FRAME_LEN_96K, in_buf_96k_f32);
        Lowpass7k_96k(in_buf_96k_f32, FRAME_LEN_96K, mem_downsampling);
        // 输出数据流长度，96k->16k时，缩短1/6
        for (i = 0, r = 0; i < FRAME_LEN_96K; i += 6, r++) {
            in_buf_16k_f32[r] = in_buf_96k_f32[i];
        }
        convert_f32_to_i16(in_buf_16k_f32, FRAME_LEN_16K, in_buf_16k_i16);
        fwrite(&in_buf_16k_i16, sizeof(short), FRAME_LEN_16K, fp_16kHz);
        convert_i16_to_f32(in_buf_16k_i16, FRAME_LEN_16K, out_buf_16k_f32);

        // 插值16k->96k
        Inter16kto96k(out_buf_16k_f32, FRAME_LEN_16K, &old_bufR_end, out_buf_96k_f32);
        // 下采样抗周期延拓
        Lowpass7k_96k(out_buf_96k_f32, FRAME_LEN_96K, mem_upsampling);
        convert_f32_to_i16(out_buf_96k_f32, FRAME_LEN_96K, out_buf_96k_i16);

        fwrite(&out_buf_96k_i16, sizeof(short), FRAME_LEN_96K, fp_96kHz);
    }
    return 0;
}